#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

int ticket = 1000;

pthread_mutex_t lock= PTHREAD_MUTEX_INITIALIZER;

void *routine(void *args)
{
    const char *id = static_cast<char *>(args);
    while (true)
    {
        pthread_mutex_lock(&lock);
        if (ticket > 0)
        {
            usleep(100);
            printf("id=%s -> ticket:%d \n", id,ticket);
            ticket--;
            //pthread_mutex_unlock(&lock);
        }
        else
        {
            break;
            //pthread_mutex_unlock(&lock);
        }
        pthread_mutex_unlock(&lock);
    }
    return nullptr;
}

int main()
{
    pthread_t t1,t2,t3;
    pthread_create(&t1, nullptr, routine, (void *)"thread_1");
    pthread_create(&t2, nullptr, routine, (void *)"thread_2");
    pthread_create(&t3, nullptr, routine, (void *)"thread_3");

    pthread_join(t1,nullptr);
    pthread_join(t2,nullptr);
    pthread_join(t3,nullptr);
    return 0;
}